package com.zimmur.service.impl.account;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Throwables;
import com.zimmur.dao.account.IPrepaidLogDao;
import com.zimmur.model.account.PrepaidLog;
import com.zimmur.model.account.UserjeLog;
import com.zimmur.service.IAccountInfoService;
import com.zimmur.service.account.IPrepaidLogService;
import com.zimmur.service.account.IUserjeLogService;
import com.zimmur.tools.DateUtils;

@Service("prepaidLogService")
public class PrepaidLogServiceImpl implements IPrepaidLogService {
	private Logger log = LoggerFactory.getLogger(PrepaidLogServiceImpl.class);
	
	@Resource
	private IPrepaidLogDao prepaidLogDao;
	@Resource
	private IUserjeLogService userjeLogService;
	@Resource
	private IAccountInfoService accountInfoService;
	
	@Override
	public boolean delete(String prepaidCode) {
		return prepaidLogDao.deleteByPrimaryKey(prepaidCode)>0?true:false;
	}

	@Override
	public boolean insert(PrepaidLog record) {
		return prepaidLogDao.insertSelective(record)>0?true:false;
	}

	@Override
	public PrepaidLog selectByCode(String prepaidCode) {
		return prepaidLogDao.selectByPrimaryKey(prepaidCode);
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor = {RuntimeException.class,Exception.class})
	public boolean updateStatus(String prepaidCode,double realPayJe, int payDate,String payMethod,String transactionId) {
		if("".equals(prepaidCode) || realPayJe<=0){
			return false;
		}
		PrepaidLog prepaidLog = selectByCode(prepaidCode);
		if(prepaidLog == null){
			return false;
		}
		try{
			String remark = "账户充值";
			PrepaidLog data = new PrepaidLog();
			data.setPrepaidCode(prepaidCode);
			data.setRealPayJe(realPayJe);
			data.setPayDate(payDate);
			data.setPayMethod(payMethod);
			data.setTransactionId(transactionId);
			//0=未充值 1=已充值
			data.setPayStatus(1);
			
			prepaidLogDao.updateByPrimaryKeySelective(data);
			
			//添加用户余额
			UserjeLog userjeLog = new UserjeLog();
			userjeLog.setUserId(prepaidLog.getUserId());
			userjeLog.setEvent("+");
			userjeLog.setEventDate(DateUtils.getNowUnixTime());
			userjeLog.setJe(realPayJe);
			userjeLog.setRemark(remark);
			
			userjeLogService.insert(userjeLog);
			
			accountInfoService.updateCurJeByUserId(prepaidLog.getUserId(), realPayJe, remark);
		}catch(Exception er){
			log.error(er.getMessage());
			Throwables.propagate(er);
		}
		
		return true;
	}

}
